package net.dntuan.simple.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

/**
 * This filter will prove that the return statement after response.sendRedirect() is not necessary
 * 
 * @author tuan.dang
 * 
 * <br>$LastChangedRevision: 37 $
 * <br>$LastChangedDate: 2014-04-07 16:55:59 +0000 (Mon, 07 Apr 2014) $
 */
public class AuthFilter implements Filter {
    private static final Logger LOGGER = Logger.getLogger(AuthFilter.class.getName());

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        LOGGER.info("filter is initialized");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String queryString = httpRequest.getQueryString();
        LOGGER.info("enter filter");
        LOGGER.info("query string: " + queryString);
        if (queryString != null && queryString.contains("auth-filter=true")) {
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            httpResponse.sendRedirect("index.html");
            LOGGER.info("direct user to the index page");
        } else {
            chain.doFilter(request, response);
        }
        LOGGER.info("go out");
    }

    @Override
    public void destroy() {
        LOGGER.info("filter is destroyed");
    }

}
